'use strict';
const db = uniCloud.database();
const collection = db.collection('users');

exports.main = async (event, context) => {
	const {
		action,
		username,
		password
	} = event;
	console.log('event : ', event);

	try {
		if (action === 'login') {
			const user = await collection.where({
				username,
				password
			}).get();

			if (user.affectedDocs < 1) {
				return {
					code: -1,
					msg: '用户名或者密码错误'
				};
			} else {
				const userInfo = user.data[0];
				delete userInfo.password; // 确保不返回密码

				return {
					code: 200,
					msg: '登录成功',
					data: userInfo
				};
			}
		} else if (action === 'register') {
      // 检查用户名是否已存在
      const existingUser = await collection.where({
        username
      }).get();
      
      if (existingUser.data.length > 0) {
        return {
          code: -5,
          msg: '用户名已存在'
        };
      }
      
      // 插入新用户
      const registerResult = await collection.add({
        username,
        password,
        createTime: new Date()
      });
      
      // 检查插入结果
      if (registerResult.id) {
        return {
          code: 200,
          msg: '注册成功'
        };
      } else {
        // 添加日志以便调试
        console.error('注册失败，返回结果:', registerResult);
        return {
          code: -4,
          msg: '注册失败，请稍后再试'
        };
      }
    } else {
			return {
				code: -2,
				msg: '未知操作'
			};
		}
	} catch (error) {
		console.error('操作错误:', error);
		return {
			code: -3,
			msg: '服务器错误，请稍后再试'
		};
	}
};